<template>
  <el-dialog
    title="编辑"
    width="30vw"
    :close-on-click-modal="false"
    @close="afterClose"
    @open="beforeOpen"
  >
    <el-form ref="formRef" :model="formData" :rules="rules">
      <el-form-item label="姓名" prop="nickName">
        <el-input
          v-model="formData.nickName"
          placeholder="请输入姓名"
          :maxlength="20"
        ></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="formData.email" placeholder="请输入"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="$emit('close')">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="loading"
        >确认</el-button
      >
    </template>
  </el-dialog>
</template>

<script setup>
import { useLoading } from "@/hooks";
import { useUserStore } from "@/store";

const emits = defineEmits(["close"]);

const formRef = ref();
const formData = ref({});
const rules = reactive({
  nickName: [{ required: true, message: "请输入姓名" }],
  email: [
    { required: true, message: "请输入邮箱" },
    { type: "email", message: "请输入正确的邮箱" },
  ],
});

const userStore = useUserStore();

const beforeOpen = async () => {
  await nextTick();
  const { nickName, email, phonenumber } = userStore.userInfo;
  formData.value = { nickName, email, phonenumber };
};

const afterClose = async () => {
  await nextTick();
  formRef.value.resetFields();
};

const $api = inject("$api");
const { loading, setLoading } = useLoading();
const handleSubmit = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      setLoading(true);
      try {
        await $api.system.updateUserInfo(formData.value);
        ElMessage.success("编辑成功");
        userStore.getUserInfo();
        emits("close");
      } finally {
        setLoading(false);
      }
    }
  });
};
</script>
